package com.example.asset.service;


import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.asset.common.Constants;
import com.example.asset.entity.SysLogininfor;
import com.example.asset.entity.SysUser;
import com.example.asset.entity.dto.SysUserDao;
import com.example.asset.entity.vo.KeyVal;
import com.example.asset.exception.ServiceException;
import com.example.asset.mapper.SysUserMapper;
import com.example.asset.utils.UtilIP;
import com.example.asset.utils.UtilPassword;
import com.example.asset.utils.UtilToken;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@RequiredArgsConstructor
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser>{

    private final SysLogininforService sysLogininforService;

    public static final Log LOG = Log.get();
    private final HttpServletRequest request;

    /**
     * 保存添加的用户信息
     *
     * @param user
     * @return
     */
    public boolean saveUser(SysUser user){
        if(user.getUserId() == null){
            user.setSalt(UtilPassword.generateSalt(16));
            user.setPassword(UtilPassword.hashPassword("123456", user.getSalt()));
        } else if(user.getUpdate() != null && user.getUpdate() == 1){
            user.setSalt(UtilPassword.generateSalt(16));
            user.setPassword(UtilPassword.hashPassword(user.getPassword(), user.getSalt()));
        }
        SysUser currentUser = UtilToken.getCurrentUser();
        if(currentUser != null){
            user.setCreateBy(currentUser.getLoginName());
        }
        user.setLoginIp(UtilIP.getIpAddress(request));
        return saveOrUpdate(user);
    }


    public SysUserDao login(SysUserDao sysUserDao, HttpServletRequest request){
        SysLogininfor sysLogininfor = new SysLogininfor();
        sysLogininfor.setLoginName(sysUserDao.getLoginName());
        sysLogininfor.setIpaddr(UtilIP.getIpAddress(request));
        UserAgent agent = UserAgentUtil.parse(request.getHeader("User-Agent"));
        if(agent != null){
            Optional.of(agent.getBrowser()).ifPresent(a -> sysLogininfor.setBrowser(a.getName()));
            Optional.of(agent.getOs()).ifPresent(o -> sysLogininfor.setOs(o.getName()));
        }
        SysUser one = getUserInfo(sysUserDao);
        if(one != null){

            boolean flag = UtilPassword.verifyPassword(sysUserDao.getPassword(), one.getPassword(), one.getSalt());

            if(flag){
                BeanUtils.copyProperties(one, sysUserDao);
                String token = UtilToken.genToken(one.getUserId().toString(), one.getPassword());
                sysUserDao.setUserType(one.getUserType());
                sysUserDao.setToken(token);
                sysUserDao.setPassword(null);
                sysLogininfor.setStatus(0);
                sysLogininfor.setMsg("登录成功");
                sysLogininforService.save(sysLogininfor);
                return sysUserDao;
            } else{
                throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
            }
        } else{
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }

    /**
     * * 注册接口 数据库查询用户名是否唯一
     * * 唯一则添加到数据库
     * * 不唯一则添加失败
     *
     * @param sysUserDao
     * @return
     */
    public SysUser register(SysUserDao sysUserDao){
        SysUser one = getUserInfo(sysUserDao);

        if(one == null){
            one = new SysUser();
            one.setLoginName(sysUserDao.getLoginName());
            one.setPassword(sysUserDao.getPassword());
            save(one);
        } else{
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }


    private SysUser getUserInfo(SysUserDao sysUserDao){
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", sysUserDao.getLoginName());
        //        queryWrapper.eq("password", sysUserDao.getPassword());
        SysUser one;
        // 处理异常情况
        try{
            one = getOne(queryWrapper);// 从数据库查询用户信息
        } catch(Exception e){
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }

    public List<KeyVal> userDepart(){
        List<KeyVal> list = this.baseMapper.userDepart();
        return list;
    }
}